package com.student.manage.util;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

public class CaptchaUtils {
    private static final int DEFAULT_LENGTH = 4;

    public static byte[] getCaptcha(String captcha) {
        DefaultKaptcha defaultKaptcha = ApplicationContextUtil.getBean(DefaultKaptcha.class);
        BufferedImage image = defaultKaptcha.createImage(captcha);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            javax.imageio.ImageIO.write(image, "png", outputStream);
            return outputStream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void getCaptcha(String captcha, HttpServletResponse response) {
        byte[] bytes = getCaptcha(captcha);
        if (bytes != null) {
            response.setContentType("image/png");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentLength(bytes.length);
            try {
                response.getOutputStream().write(bytes);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static String getCaptcha(HttpServletRequest request, HttpServletResponse response) {
        String captcha = StringUtil.getRandomString(DEFAULT_LENGTH);
        request.getSession().setAttribute("captcha_code", captcha);
        getCaptcha(captcha, response);
        return captcha;
    }
}
